package cn.shyouchi.wuguanjia.android.ui.patrol.begin;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jeanboy.cropview.cropper.CropperHandler;
import com.jeanboy.cropview.cropper.CropperManager;
import com.jeanboy.cropview.cropper.CropperParams;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.patrol.PatrolApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.event.PatrolChangeEvent;
import cn.shyouchi.wuguanjia.android.event.SelManagerEvent;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.utils.DisplayUtil;
import cn.shyouchi.wuguanjia.android.utils.LogUtil;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class PatrolSubmitActivity extends BaseActivity implements BGASortableNinePhotoLayout.Delegate,
        CropperHandler {


    private static final int REQUEST_CODE_PHOTO_PREVIEW = 2;

    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.tv_report_time)
    TextView mTvReportTime;
    @BindView(R.id.tv_report_time_diff)
    TextView mTvReportTimeDiff;
    @BindView(R.id.photo_snpl)
    BGASortableNinePhotoLayout mPhotoSnpl;
    //    @BindView(R.id.tv_report_content)
//    TextView mTvReportContent;
    @BindView(R.id.group_contents)
    LinearLayout mGroupContents;


    String path;
    ArrayList<String> photos = new ArrayList<>();
    PatrolRingDesEntity.ResultMessageBean.InfoBean entity;
    PatrolApi mPatrolApi;
    @BindView(R.id.rb_normal)
    RadioButton mRbNormal;

    @BindView(R.id.rb_error)
    RadioButton mRbError;
    @BindView(R.id.edit_error_name)
    EditText mEditErrorName;
    @BindView(R.id.edit_error_content)
    EditText mEditErrorContent;
    @BindView(R.id.photo_snpl_error)
    BGASortableNinePhotoLayout mPhotoSnplError;
    @BindView(R.id.lin_error)
    LinearLayout mLinError;


    ArrayList<String> errorPhotos = new ArrayList<>();
    @BindView(R.id.rv_leader)
    RecyclerView mRvLeader;

    PatrolManagerAdapter mPatrolManagerAdapter;
    List<PatrolManagerEntity.ResultMessageBean> managers = new ArrayList<>();
    @BindView(R.id.rel_sel_manager)
    RelativeLayout mRelSelManager;


    @Override
    public int initContentView() {
        return R.layout.activity_patrol_submit;
    }

    @Override
    public void initInjector() {
        entity = getIntent().getParcelableExtra("info");
        path = getIntent().getStringExtra("path");
        photos.add(path);
        mPatrolApi = new PatrolApi(mContext);
        CropperManager.getInstance().build(this);
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setTitle(getTitle().toString());
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(mTopBar.getToolbar());

        mTvReportTime.setText(entity.getInspectiontime());
        mTvReportTimeDiff.setText(entity.getInspectionname());
//        mTvReportContent.setText(entity.getInspectioncontent());
        mPhotoSnpl.init(this);
        mPhotoSnpl.setData(photos);
        mPhotoSnpl.setDelegate(this);
        mPhotoSnpl.setIsSortable(false);
        mPhotoSnpl.setDeleteDrawableResId(R.drawable.photo_del_bg);

        EventBus.getDefault().register(this);

        mPatrolManagerAdapter = new PatrolManagerAdapter(managers);
        mRvLeader.setAdapter(mPatrolManagerAdapter);
        mRvLeader.setLayoutManager(new LinearLayoutManager(mContext));

        mPhotoSnplError.init(this);
        mPhotoSnplError.setDelegate(this);
        mPhotoSnplError.setIsSortable(false);

        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        String[] strings = entity.getInspectioncontent().split("\n");
        for (String s : strings) {
            CheckBox checkBox = new CheckBox(mContext);
            checkBox.setText(s);
            checkBox.setButtonDrawable(R.drawable.selector_checkbox_check);
            checkBox.setLayoutParams(params);
            checkBox.setPadding(DisplayUtil.dip2px(mContext, 5), DisplayUtil.dip2px(mContext, 5), DisplayUtil.dip2px(mContext, 5), DisplayUtil.dip2px(mContext, 5));
            mGroupContents.addView(checkBox);
        }


        mRbError.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mLinError.setVisibility(isChecked ? ViewGroup.VISIBLE : ViewGroup.GONE);
            }
        });


    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    @OnClick(R.id.btn_save)
    public void onClick() {

        if (checkTask()) {

            Map<String, Object> data = new HashMap<>();
            data.put("inspectionpointid", entity.getId());
            data.put("situation", mRbNormal.isChecked() ? "1" : "0");
            data.put("completed", 1);
//            List<String> images = new ArrayList<>();
//            images.add(imageFileToBase64(path));
//            data.put("image", images);


            if (mRbError.isChecked()) {
                Map<String, Object> errorMap = new HashMap<>();
                List<Integer> users = new ArrayList<>();
                for (PatrolManagerEntity.ResultMessageBean b : managers) {
                    users.add(b.getId());
                }
//                List<String> warranty_images = new ArrayList<>();

//                for (String p : mPhotoSnplError.getData()) {
//                    warranty_images.add(imageFileToBase64(p));
//                }


                errorMap.put("userid", users);
                errorMap.put("title", mEditErrorName.getText().toString());

                errorMap.put("content", mEditErrorContent.getText().toString());
//                errorMap.put("warranty_image", warranty_images);
                data.put("error", errorMap);
            }


            LogUtil.json(data);


//            mPatrolApi.submitPatrol(data)
//                    .subscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
//                        @Override
//                        public void onNext(BaseRequestResult result) {
//                            ToastUtil.showToast(result.getResultMessage());
//                            EventBus.getDefault().post(new PatrolChangeEvent());
//                            finish();
//                        }
//                    });


            mPatrolApi.submitPatrols(data, path, mPhotoSnplError.getData())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
                        @Override
                        public void onNext(BaseRequestResult result) {
                            ToastUtil.showToast(result.getResultMessage().toString());
                            EventBus.getDefault().post(new PatrolChangeEvent());
                            finish();
                        }
                    });

//            mPatrolApi.submitPatrol(String.valueOf(entity.getId()),
//                    mRbNormal.isChecked() ? "1" : "0",
//                    "1",
//                    path,
//                    mPhotoSnplError.getData())
//                    .subscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
//                        @Override
//                        public void onNext(BaseRequestResult result) {
//                            ToastUtil.showToast(result.getResultMessage());
//                            EventBus.getDefault().post(new PatrolChangeEvent());
//                            finish();
//                        }
//                    });


        } else {
            ToastUtil.showToast("有任务还没确认，请勾选确认！");

        }


    }


    private boolean checkTask() {
        for (int i = 0; i < mGroupContents.getChildCount(); i++) {
            CheckBox cb = (CheckBox) mGroupContents.getChildAt(i);
            if (!cb.isChecked()) {
                return false;
            }
        }
        return true;
    }


    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        CropperManager.getInstance().pickFromCamera();
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        errorPhotos.remove(position);
        mPhotoSnplError.setData(errorPhotos);

    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout layout, View view, int position, String model, ArrayList<String> models) {
        startActivityForResult(BGAPhotoPickerPreviewActivity.newIntent(this, layout.getMaxItemCount(), models, models, position, false), REQUEST_CODE_PHOTO_PREVIEW);

    }


    private String imageFileToBase64(String path) {
        Bitmap bm = BitmapFactory.decodeFile(path);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 50, baos); //bm is the bitmap object
        byte[] b = baos.toByteArray();
        String base64 = Base64.encodeToString(b, Base64.DEFAULT);
        return base64;
    }


    @OnClick(R.id.rel_sel_manager)
    public void onSelClick() {
        startActivity(new Intent(mContext, PatrolSelManagerActivity.class));
    }


    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public CropperParams getParams() {
        return new CropperParams(720, 720);
    }

    @Override
    public void onCropped(Uri uri) {
        errorPhotos.add(uri.getPath());
        mPhotoSnplError.setData(errorPhotos);

    }

    @Override
    public void onCropCancel() {

    }

    @Override
    public void onCropFailed(String msg) {
        LogUtil.e(msg);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        LogUtil.json(data);

        CropperManager.getInstance().handlerResult(requestCode, resultCode, data, false);


    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSelManager(SelManagerEvent event) {
        managers.addAll(event.getManagers());
        mPatrolManagerAdapter.notifyDataSetChanged();
    }


}
